home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / PROGRAMM / DB_CLIPP / 2510.ZIP / TRSOURCE.EXE / BASE.C < prev    next >
C/C++ Source or Header  |  1990-10-22  |  2KB  |  63 lines

  1. /*********
  2. *  base.c by Leonard Zerman
  3. * Placed in the public domain by Tom Rettig Associates, 10/22/1990.
  4. *
  5. *  Syntax: BASE( <expN>, <expN> )
  6. *  Return: <expC> value of <decimal number> in the mathematical 
  7. *          format of <base>. Both parameters are <expN>. Maximum  
  8. *          <base> is 36, Minimum <base> is 2.
  9. *  Note  : Changes negative number to positive.
  10. ********/
  11.  
  12. #include "trlib.h"
  13.  
  14. TRTYPE base()                                /* declare the base function */
  15. {
  16.     
  17.     static char funcname[] = {"base"};      /* program name for errors */                 
  18.     static char lookup[]   = {"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
  19.     static char result[33];
  20.     int    i, j;
  21.     long   dec, base;
  22.  
  23.     if (PCOUNT == 2 && ISNUM(1) && ISNUM(2))  /* get parms from caller */
  24.     {                  
  25.         base = _parnl(1) ;
  26.         dec  = _parnl(2);
  27.     }
  28.     else                                     
  29.     {
  30.          
  31.          _retc( _tr_errmsgs(funcname, E_SYNTAX) );  /* return an error */      
  32.          return;                                /* return from program */     
  33.     }
  34.  
  35.     if ( base > 36 || base < 2 || dec > TWO_BILLION )  /* catch errors */
  36.     {
  37.         _retc( _tr_errmsgs(funcname, E_SYNTAX) );   /* return an error */      
  38.         return;                                 /* return from program */     
  39.     }
  40.  
  41.     dec = ABS( dec );                           /* take absolute value */
  42.     i = j = 0;                                      /* initialize vars */
  43.  
  44.     do
  45.     {
  46.         i = (int)( dec % base );           /* MOD to get look-up value */
  47.         result[j++] = lookup[i];      /* assign look-up char to result */
  48.         dec /= base;                    /* decrement value dec by base */
  49.  
  50.     } while ( dec > 0 );                /* until no decimal value left */
  51.  
  52.     result[j] = NULLC;              /* terminate string with NULL char */
  53.  
  54.     for (i = 0, j = _tr_strlen( result ) - 1; i < j; i++, j--)
  55.     {
  56.         result[i] ^= result[j];          /* reverse the string */
  57.         result[j] ^= result[i];          /* with the two chars */
  58.         result[i] ^= result[j];              /* using XOR swap */
  59.     }
  60.   
  61.     _retc(result);                        /* return the result */
  62. }
  63.